package com.gaohe.interceptor;

import com.alibaba.fastjson.JSON;
import com.gaohe.common.BaseContext;
import com.gaohe.common.PathMatcher;
import com.gaohe.common.R;
import com.gaohe.common.S;
import com.gaohe.pojo.Admin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //获取 session
        //HttpSession session = request.getSession();
        //获取请求 uri
        String uri = request.getRequestURI();
        //判断是否需要处理
        boolean check = PathMatcher.check(uri);
        if (check){
            log.info("本次请求不需要处理：{}",uri );
            return true;
        }
        //判断登录状态 登录--放行
        //Object id = session.getAttribute(S.SESSION_KEY);
        String uid = request.getHeader("auth");
        Object redisId = null;
        if (ObjectUtils.isNotEmpty(uid)){
             redisId = redisTemplate.opsForValue().get("auth"+uid);
        }
        if (ObjectUtils.isNotEmpty(redisId)){
            log.info("用户已登录，放行");
            BaseContext.setCurrentId((Long) redisId);
            return true;
        }
        log.info("用户未登录");
        //返回未登录结果
        response.setStatus(401);
        response.getWriter().write(JSON.toJSONString(R.error(S.NOT_LOGIN)));
        return false;
    }
}
